package com.ar.studyapp;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.ar.adapter.SubjectAdapter;
import com.ar.customview.FavoriteCharacterDialogFragment;
import com.ar.customview.IFavoriteCharacterDialogListener;
import com.ar.datahandler.StringJSONHandler;
import com.ar.network.NetworkUtility;
import com.ar.network.ParametersBuilder;
import com.ar.network.RestConnector;
import com.ar.util.AppUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import eu.inmite.android.lib.dialogs.SimpleDialogFragment;

/**
 * The Class CategoriesActivity.
 * 
 * @author anh
 */
public class CategoriesActivity extends BaseActivity implements
		IFavoriteCharacterDialogListener {

	private ListView listViewSubjects;

	/** The adapter for grid view. */
	private SubjectAdapter subjectAdapter;

	private ProgressDialog progressDialogOnLoad;

	private String[] difficult;

	private StringJSONHandler jsonWorker;

	private JsonHttpResponseHandler getQuizsHandler;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.studyapp.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.studyapp.BaseActivity#displayActivity()
	 */
	@Override
	protected void displayActivity() {
		setContentView(R.layout.activity_categories);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.studyapp.BaseActivity#initViews()
	 */
	@Override
	protected void initViews() {
		listViewSubjects = (ListView) findViewById(R.id.listView_subject);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.studyapp.BaseActivity#initVariables()
	 */
	@Override
	protected void initVariables() {
		difficult = new String[] { "Khó", "Trung bình", "Dễ" };
		subjectAdapter = new SubjectAdapter(this, AppUtil.listSubject);
		jsonWorker = new StringJSONHandler();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.studyapp.BaseActivity#initActions()
	 */
	@Override
	protected void initActions() {
		listViewSubjects.setAdapter(subjectAdapter);
		listViewSubjects.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int pos,
					long id) {
				setCurrentCategoryId(subjectAdapter.getCategoryId(pos));
				setCurrentSubjectName(subjectAdapter.getSubjectName(pos));
				showDifficultPickerDialog(getActivityInstance());
			}
		});
		getQuizsHandler = new JsonHttpResponseHandler() {

			public void onSuccess(JSONObject response) {
				String jsonResponse = response.toString();
				progressDialogOnLoad.dismiss();
				if (jsonWorker.checkError(jsonResponse) == false) {
					if (!jsonWorker.checkDataAvailable(jsonResponse)) {
						showNoDataDialog(getActivityInstance());
					} else {
						String title = new String(getCurrentSubjectName() + "-"
								+ getCurrentDiffName());
						Intent intent = new Intent(getBaseContext(),
								ExamActivity.class);
						intent.putExtra("title", title);
						intent.putExtra("data", jsonResponse.toString());
						startActivity(intent);
					}
				} else {
					Toast.makeText(getApplicationContext(),
							jsonWorker.getErrorMessage(jsonResponse),
							Toast.LENGTH_LONG).show();
				}
			};

			@Override
			public void onFailure(Throwable error, String content) {
				progressDialogOnLoad.dismiss();
				NetworkUtility.showTimeOutDialog(getActivityInstance());
			}
		};
		/*
		 * gridViewCategory.setOnItemClickListener(new OnItemClickListener() {
		 * 
		 * @Override public void onItemClick(AdapterView<?> arg0, View v, int
		 * position, long id) {
		 * 
		 * JSONObject jsonResponse = new JSONObject(); try { JSONArray
		 * jsonDifficults = new JSONArray(); JSONObject jsonObject1 = new
		 * JSONObject(); jsonObject1.put("id", "1"); jsonObject1.put("name",
		 * "extreme"); jsonObject1.put("code", "1"); JSONObject jsonObject2 =
		 * new JSONObject(); jsonObject2.put("id", "2"); jsonObject2.put("name",
		 * "high"); jsonObject2.put("code", "2"); JSONObject jsonObject3 = new
		 * JSONObject(); jsonObject3.put("id", "3"); jsonObject3.put("name",
		 * "low"); jsonObject3.put("code", "3");
		 * jsonDifficults.put(jsonObject1); jsonDifficults.put(jsonObject2);
		 * jsonDifficults.put(jsonObject3); jsonResponse.put("difficults",
		 * jsonDifficults);
		 * 
		 * if (((SubCategory) v).getSubjectId().equals("3")) { try { JSONObject
		 * jsonObject = new JSONObject(); jsonObject.put(NetworkUtility.HANDLE,
		 * NetworkUtility.ONERROR); jsonObject.put(NetworkUtility.ERROR_CODE,
		 * "1"); jsonObject.put(NetworkUtility.ERROR_MESSAGE,
		 * "Data not found!"); jsonResponse = new
		 * JSONObject(jsonObject.toString()); } catch (JSONException e) { //
		 * TODO Auto-generated catch block e.printStackTrace(); } }
		 * 
		 * } catch (JSONException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 * 
		 * if (jsonHandler.checkError(jsonResponse.toString()) == false) {
		 * Intent intent = new Intent(getApplicationContext(),
		 * LevelOptionsActivity.class); intent.putExtra("title", ((SubCategory)
		 * v).getSubjectName()); intent.putExtra("categoryId", ((SubCategory)
		 * v).getSubjectId()); intent.putExtra("difficults",
		 * jsonResponse.toString()); startActivity(intent); } else {
		 * if(jsonHandler.getErrorCode(jsonResponse.toString()).equals("1"))
		 * NetworkUtility.showDialog(getActivityInstance(), "Error",
		 * jsonHandler.getErrorMessage(jsonResponse.toString())); } } });
		 */

	}

	@Override
	protected void setUpActionBar() {

	}

	private void showDifficultPickerDialog(Context context) {
		FavoriteCharacterDialogFragment.show(
				(FragmentActivity) getActivityInstance(), "Chọn độ khó",
				difficult);

	}

	private void showNoDataDialog(Context context) {
		SimpleDialogFragment.createBuilder(this, getSupportFragmentManager())
				.setTitle("Không có dữ liệu")
				.setMessage("Hiện tại chưa có đề thi phù hợp !").show();
	}

	@Override
	public void onListItemSelected(String value, int number) {
		if (NetworkUtility.checkNetworkState(getBaseContext())) {
			setCurrentDiffName(difficult[number]);
			setCurrentDifficultId("" + (number + 1));
			startRequest(getCurrentCategoryId(), getCurrentDifficultId());
		} else
			NetworkUtility.showNoNetworkDialog(getActivityInstance());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.network.OnResponseListener#onResponse(java.lang.String)
	 */

	private void startRequest(String category_id, String difficultId) {
		// SOAPConnector connector = new
		// SOAPConnector(RequestBuilder.BuildOnLoadRequest(category_id,
		// difficultId));
		// connector.setOnResponseListener(this);
		progressDialogOnLoad = ProgressDialog.show(this, "Đang tải đề thi",
				"Bạn vui lòng chờ …");
		// connector.startRequest();
		RestConnector
				.get(NetworkUtility.GET_QUIZS_URL, ParametersBuilder
						.BuildGetQuizsParams(category_id, difficultId),
						getQuizsHandler);
	}

	/*
	 * @Override public void onResponse(String jsonResponse) {
	 * progressDialogOnLoad.dismiss(); if (jsonWorker.checkError(jsonResponse)
	 * == false) { String title = new String(getCurrentSubjectName() + "-" +
	 * getCurrentDiffName()); Intent intent = new Intent(this,
	 * ExamActivity.class); intent.putExtra("title", title);
	 * intent.putExtra("data", jsonResponse.toString()); startActivity(intent);
	 * } else { Toast.makeText(getApplicationContext(),
	 * jsonWorker.getErrorMessage(jsonResponse), Toast.LENGTH_LONG) .show(); } }
	 * 
	 * 
	 * (non-Javadoc)
	 * 
	 * @see com.ar.network.OnResponseListener#onRequestTimeOut()
	 * 
	 * @Override public void onRequestTimeOut() {
	 * progressDialogOnLoad.dismiss(); NetworkUtility.showTimeOutDialog(this); }
	 */

}